// import { resolve } from "url";
import * as path from "path";
import * as fs from 'fs'; 


async function readFileAsync(path: string, readCode = 'utf-8',) {
    return new Promise((resolve, reject) => {
        fs.readFile(path, readCode, (err, data) => {
            if(err){
                 reject(err)
            } else {
                 resolve(data)
            }         
        })
    })
}

async function writeFileAsync(path: string, content: string) {
    console.log(path, content);
    return new Promise((resolve, reject) => {
        fs.writeFile(path, content, (err) => {
            if(err) {
                reject({
                    err: err,
                    status: 'error'
                });
            }

            resolve({
                status: 'success'
            })
        })
    })
}

function mkdirs(dirname: string, callback: any) {  
    fs.exists(dirname, function (exists) {  
        if (exists) {  
            callback();  
        } else {  
            // console.log(path.dirname(dirname));  
            mkdirs(path.dirname(dirname), function () {  
                fs.mkdir(dirname, callback);  
                console.log('在' + path.dirname(dirname) + '目录创建好' + dirname  +'目录');
            });  
        }  
    });  
}  

async function appendFile(path: string, content: string, code = 'utf-8') {
    const filesExist = await fsExists(path);
    console.log(filesExist);
    if(!filesExist) {
        return writeFileAsync(path, content);
    }
    return new Promise((resolve, reject) => {
        fs.appendFile(path, content, code, (error) => {
            if(error) {
                reject({
                    status: 'fail',
                    data: error
                })
            } 
            resolve({
                status: 'success',
                data: '追加成功'
            })
        })
    })
}

async function fsExists(path: string) {
    return new Promise((resolve, reject) => {
        fs.exists(path, (exist) => {
            resolve(exist);
        })
    })
}

export {
    readFileAsync,
    writeFileAsync,
    mkdirs,
    appendFile
}